<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeName - 0" :space="200" finish-status="success" align-center>
        <el-step title="商品信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页 -->
      <el-form
        ref="addFormRef"
        label-width="80px"
        :model="addForm"
        :rules="addFormRules"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeName"
          @tab-click="handleClick"
          :before-leave="beforeLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="(item,i) in manyData" :key="i" :label="item.attr_name">
              <!-- 双向同步attr_name数组的 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="item2" v-for="(item2,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headerobj"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor  v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="add" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%">
        <img :src="previewUrl" alt width="100%" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 步骤条和tab面板绑定的数据
      activeName: "0",
      addForm: {
        goods_name: "111",
        goods_cat: [],
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        pics: [],
        goods_introduce: "",
        // 动态参数和静态属性处理完之后新增到该数组中
        attrs: [],
      },
      //   级联选择框的数据根源
      cateList: [],
      // 级联选择框的配置信息
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 表单校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "选择商品分类", trigger: "blur" },
        ],
      },
      //   商品参数
      manyData: [],
      // 商品属性
      onlyData: [],
      //   配置请求头信息
      headerobj: {
        Authorization: sessionStorage.getItem("token"),
      },
      // 控制预览照片的预览值
      previewDialogVisible: false,
      // 预览照片url
      previewUrl: "",
    };
  },
  methods: {
    //   上传成功的图片点击预览的时候触发的钩子
    handlePreview(file) {
      //   console.log(file);
      // 图片的完整路径
      this.previewUrl = file.response.data.url;
      this.previewDialogVisible = true;
    },
    //   移除图片触发的钩子
    handleRemove(file) {
      //   console.log(file);
      // 将对应删除图片的临时路径获取到
      const i = this.addForm.pics.findIndex(
        (item) => item.pic === file.response.data.tmp_path
      );
      // 截取数组元素
      this.addForm.pics.splice(i, 1);
    },
    //   图片上传成功触发的钩子
    handleSuccess(response) {
      //   console.log(file);
      //   console.log(response);
      // 将上传的图片保存在addForm中的pic数组中
      this.addForm.pics.push({
        pic: response.data.tmp_path,
      });
    },
    addGoods() {
      this.$refs.addFormRef.validate(async (boo) => {
        if (!boo) {
          return this.$message.error("请填完整信息后提交");
        }
        this.manyData.forEach((item) => {
          let obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(obj);
        });
        this.onlyData.forEach((item) => {
          let obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          }
          this.addForm.attrs.push(obj);
        });
        // var newform = _.cloneDeep(this.addForm);
        var newform = JSON.parse(JSON.stringify(this.addForm));
        newform.goods_cat = newform.goods_cat.join(",");
        console.log(newform);
        const { data: res } = await this.$http.post("goods", newform);
        if (res.meta.status !== 201) {
          return this.$message.error("添加商品失败");
        }
        this.$message.success("添加商品成功");
        // 编程式导航跳转到商品列表页面
        this.$router.push("/goods");
      });
    
  },
    async getData(sel) {
      const { data: res } = await this.$http.get(
        `categories/${this.addForm.goods_cat[2]}/attributes`,
        { params: { sel } }
      );
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }
      //   动态参数赋值
      return res.data;
    },
    async handleClick() {
      //   console.log(this.activeName);
      // 在当前方法中判断用户是否点击了对应需要获取数据的tab页签
      // 根据点击的具体activeName在发送请求
      if (this.activeName === "1") {
        // 获取动态参数
        // const { data: res } = await this.$http.get(`categories/${this.addForm.goods_cat[2]}/
        // attributes`,{params:{sel:'many'}});
        //   if (res.meta.status !== 200) {
        //     return this.$message.error("获取商品分类失败");
        //   }
        //   this.manyData = res.data;
        this.manyData = await this.getData("many");
        this.manyData.forEach((item) => {
          item.attr_vals = item.attr_vals.split(" ");
        });
      } else if (this.activeName === "2") {
        // 获取动态参数
        // const { data: res } = await this.$http.get(`categories/${this.addForm.goods_cat[2]}/
        // attribute`,{params:{sel:'only'}});
        //   if (res.meta.status !== 200) {
        //     return this.$message.error("获取商品分类失败");
        //   }
        //   this.onlyData = res.data;
        // 获取静态属性
        this.onlyData = await this.getData("only");
      }
    },
    // 获取级联选择器数据的方法
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }
      this.cateList = res.data;
    },
    // 级联选择框触发事件
    handleChange() {
      // 只允许为三级分类设置相关参数

      if (this.addForm.goods_cat.length !== 3) {
        return (this.addForm.goods_cat = []);
      }
    },
    beforeLeave(newTab, oldTab) {
      // newTab表示的即将要跳转的tab页签 oldTab是为跳转之前的tab页
      if (oldTab === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
},

  created() {
    //   调用获取级联函数选择器的数据
    this.getCateList();
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin-top: 20px;
}
.el-checkbox {
  margin: 10px;
}
</style>